package com.itcast.googleplay.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.itcast.googleplay.DetailActivity;
import com.itcast.googleplay.R;
import com.itcast.googleplay.adapter.MyBaseAdapter;
import com.itcast.googleplay.adapter.MyBaseAdapter1;
import com.itcast.googleplay.adapter.MyPagerAdapter;
import com.itcast.googleplay.application.MyApplication;
import com.itcast.googleplay.domain.AppInfo;
import com.itcast.googleplay.domain.HomeBean;
import com.itcast.googleplay.holder.BaseHolder;
import com.itcast.googleplay.holder.HomeHolder;
import com.itcast.googleplay.protocol.HomeProtocol;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;

public class HomeFragment extends BaseFragment {
	private PullToRefreshListView prlv;
	private BaseHolder holder;
	private HomeBean homeData;
	private ListView lv;
	private HomeAdapter myBaseAdapter;
	private LinearLayout llContainer;
	protected String TAG = "HomeFragment";
	private int index;
	private ViewPager vp;
	private RunnableTask runnableTask;
	
	@Override
	public ResultState onSubLoad() {
		HomeProtocol homeProtocol = new HomeProtocol();
		homeData = homeProtocol.getData("home", 0, "");
		//homeData为null------>请求失败
		//homeData中的集合size为0------->服务器没有数据
		//homeData中的集合size大于0------->成功
		if(homeData!=null){
			if(homeData.list!=null && homeData.list.size()>0){
				return ResultState.STATE_SUCCESSED;
			}else{
				return ResultState.STATE_EMPTY;
			}
		}else{
			return ResultState.STATE_ERROR;
		}
	}

	@Override
	public View onCreateSubSuccessedView() {
		View view = UIUtils.inflate(R.layout.layout_listview);
		prlv = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
		
		
		
		prlv.setMode(Mode.BOTH);//支持下拉刷新和上拉加载
//		prlv.setMode(Mode.PULL_FROM_END);如果模式为PULL_FROM_END则支持上拉加载
//		prlv.setMode(Mode.PULL_FROM_START);如果模式为PULL_FROM_START则支持下拉刷新
		
		prlv.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if(prlv.getCurrentMode() == Mode.PULL_FROM_START){
					//1.刷新,将原有数据删除,加入请求的最新的数据
					homeData.list.clear();
					//2.发送请求,获取服务器的最新数据
					subShow();
					//3.刷新数据适配器
					myBaseAdapter.notifyDataSetChanged();
					//4.隐藏刷新头
					prlv.onRefreshComplete();
				}else{
					//2.加载,保留原有数据,加入本次请求的下一页数据   index = 0  index = 20  index = 40 
					new Thread(){
						public void run() {
							HomeProtocol homeProtocol = new HomeProtocol();
							HomeBean moreData = homeProtocol.getData("home",homeData.list.size(), "");
							if(moreData.list!=null && moreData.list.size()>0){
								homeData.list.addAll(moreData.list);
								UIUtils.runInMainThread(new Runnable() {
									@Override
									public void run() {
										//通知数据适配器刷新
										myBaseAdapter.notifyDataSetChanged();
										prlv.onRefreshComplete();
									}
								});
							}else{
								UIUtils.runInMainThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(UIUtils.getContext(), "没有更多数据了...", 0).show();
										prlv.onRefreshComplete();
									}
								});
							}
						};
					}.start();
					
				}
			}
		});
		//获取ListView
		lv = prlv.getRefreshableView();
		
		View viewHeader = UIUtils.inflate(R.layout.layout_list_view_header);
		vp = (ViewPager) viewHeader.findViewById(R.id.vp);
		
		MyPagerAdapter myPagerAdapter = new MyPagerAdapter(homeData.picture);
		vp.setAdapter(myPagerAdapter);

		lv.addHeaderView(viewHeader);
		
		//去掉listView的分割线
		lv.setDivider(null);
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
				AppInfo appInfo = homeData.list.get(position-2);
				Intent intent = new Intent(UIUtils.getContext(),DetailActivity.class);
				//开启界面的是,需要告知详情界面需要获取那个应用的详情数据(有缘网,酷狗应用.......)
				intent.putExtra("packagename", appInfo.packageName);
				startActivity(intent);
			}
		});
		
		//1.	和服务器端工程师约定好,顶部轮播图的图片比例需要是2.65:1
		//2.	2.65就是屏幕的宽度,1就是屏幕的图片的高度
		
		
		//3.获取屏幕的宽度
		int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		int height = (int)(width/2.65+0.5f);
		//4.layoutParams指定viewpager宽高大小的参数
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
		vp.setLayoutParams(layoutParams);
		//指定起始位置
		Log.i(TAG, "(Integer.MAX_VALUE/2-7) = "+(Integer.MAX_VALUE/2-7));
		vp.setCurrentItem(Integer.MAX_VALUE/2-7);
		
		
		llContainer = (LinearLayout) viewHeader.findViewById(R.id.ll_container);
		
		LayoutParams llParams = new LinearLayout.LayoutParams
				(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		llParams.rightMargin = UIUtils.dip2px(6);
		llParams.bottomMargin = UIUtils.dip2px(6);
		
		for (int i = 0; i < homeData.picture.size(); i++) {
			ImageView imageView = new ImageView(UIUtils.getContext());
			if(i == 0){
				//第一个点,选中
				imageView.setBackgroundResource(R.drawable.indicator_selected);
			}else{
				imageView.setBackgroundResource(R.drawable.indicator_normal);
			}
			
			//指定imageView添加的规则是竖直距离底部,和水平间距各10个dp
//			imageView.setLayoutParams(llParams);
			//在线性布局中添加点,指定imageView添加的规则是竖直距离底部,和水平间距各10个dp
			llContainer.addView(imageView, llParams);
		}
		
		
		vp.setOnPageChangeListener(new OnPageChangeListener() {
			//Integer.MAX_VALUE/2-7%homeData.list.size()
			@Override
			public void onPageSelected(int position) {
//				100%8 = 12*8+4	4
//				101%8 = 12*8+5	5	
//				102%8 = 12*8+6	6	
//				103%8 = 12*8+7	7	
//				104%8 = 13*8+0	0	
//				105%8 = 13*8+1	1	
//				106%8 = 13*8+2	2	
//				107%8 = 13*8+3	3	
						
				index = position%homeData.picture.size();
				Log.i(TAG , "position = "+position);
				Log.i(TAG , "index = "+index);
				
				for (int i = 0; i < homeData.picture.size(); i++) {
					if(index == i){
						//设置选中颜色
						llContainer.getChildAt(index).setBackgroundResource(R.drawable.indicator_selected);
					}else{
						//设置未选中颜色
						llContainer.getChildAt(i).setBackgroundResource(R.drawable.indicator_normal);
					}
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		
		myBaseAdapter = new HomeAdapter(homeData.list);
		lv.setAdapter(myBaseAdapter);
		
		//让轮播图自动滚动
		startScroll();
		
		return view;
	}
	private void startScroll() {
		//在准备开始滚动前,如果有handler维护了任务,也将其移除掉,保证此页面中的任务只有1个
		UIUtils.getHandler().removeCallbacksAndMessages(null);
		
		//创建一个RunnableTask的子类对象,调用自定义的start方法
		runnableTask = new RunnableTask();
		runnableTask.start();
	}
	class RunnableTask implements Runnable{

		@Override
		public void run() {
			//在维护第二个任务的时候,将第一个任务移除掉
//			UIUtils.getHandler().removeCallbacksAndMessages(null);
			UIUtils.getHandler().removeCallbacks(this);
			
			//1.获取当前viewpager指向的界面索引
			int currentItem = vp.getCurrentItem();
			//2.指定viewpager索引加1后,进行轮训
			vp.setCurrentItem(++currentItem);
			//3.无限轮训,2秒钟后轮训一次
			UIUtils.getHandler().postDelayed(this, 4000);
		}

		public void start() {
			//在此start方法中去调用run方法,让任务开始执行
			//1.获取handler对象,调用post方法,此post方法就会去调用runnable中的run方法
			//调用postDelayed方法就在handler中维护了一个任务1
			UIUtils.getHandler().postDelayed(this, 4000);
		}
		
	}
	
	class HomeAdapter extends MyBaseAdapter<AppInfo>{
		public HomeAdapter(List<AppInfo> list) {
			super(list);
		}
		//返回首页需要用到的holder对象
		@Override
		public BaseHolder getSubBaseholder() {
			//new HomeHolder的时候调用了父类BaseHolder的构造方法
			//1.创建了homeholder对象,而且homeholder继承至baseHolder
			//2.convertView = initView();将布局xml---->convertView对象,findViewByid也在initView方法中处理
			//3.convertView.setTag(this);
			return new HomeHolder();
		}
	}
	
	//当fragment不可见的时候,移除在fragment中维护的让轮播图滚动的任务
	@Override
	public void onStop() {
		if(runnableTask!=null){
			UIUtils.getHandler().removeCallbacks(runnableTask);
		}
		super.onStop();
	}
	
	//当fragment销毁的时候,移除在fragment中维护的让轮播图滚动的任务
	@Override
	public void onDestroy() {
		if(runnableTask!=null){
			UIUtils.getHandler().removeCallbacks(runnableTask);
		}
		super.onDestroy();
	}
}
